package com.sgdh.project.terminal.terminal.service.impl;

import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Date;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JFrame;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sgdh.common.utils.security.ShiroUtils;
import com.sgdh.common.utils.text.Convert;
import com.sgdh.netty.constant.ClientNetty;
import com.sgdh.netty.constant.MyPanel;
import com.sgdh.netty.constant.RemoteDesktop;
import com.sgdh.netty.constant.RemoteKeyListener;
import com.sgdh.netty.constant.RemoteMouseListener;
import com.sgdh.netty.handler.ClientHandler;
import com.sgdh.netty.handler.ImageDecoder;
import com.sgdh.project.terminal.terminal.domain.Terminal;
import com.sgdh.project.terminal.terminal.mapper.TerminalMapper;
import com.sgdh.project.terminal.terminal.service.ITerminalService;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

/**
 * 终端管理 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class TerminalServiceImpl implements ITerminalService
{
    private static final Logger log = LoggerFactory.getLogger(TerminalServiceImpl.class);

    @Autowired
    private TerminalMapper terminalMapper;


    /**
     * 根据条件分页查询终端列表
     * 
     * @param Terminal 终端信息
     * @return 终端信息集合信息
     */
	@Override
	public List<Terminal> selectTerminalList(Terminal terminal) {
		if(!ShiroUtils.getSysUser().isAdmin()) {
			terminal.getParams().put("userId", ShiroUtils.getUserId());
		}
        return terminalMapper.selectTerminalList(terminal);
	}

	/**
     * 新增终端
     * 
     * @param Terminal 终端信息
     * @return 操作结果
     */
	@Override
	public int insertTerminal(Terminal terminal) {
		int result = 0;
		try {
			terminal.setCreateBy(ShiroUtils.getSysUser().getUserId().toString());
			terminal.setCreateTime(new Date());
			result = terminalMapper.insertTerminal(terminal);
		} catch (Exception e) {
			result = 0;
			e.printStackTrace();
		}
		return result;
	}

	/**
     * 根据终端Id获取终端明细
     * 
     * @param id 终端id
     * @return Terminal  终端详情
     */
	@Override
	public Terminal selectTerminalById(int id) {
		// TODO Auto-generated method stub
		return terminalMapper.selectTerminalById(id);
	}

	/**
     * 修改保存终端信息
     * 
     * @param Terminal 终端信息
     * @return 修改操作结果
     */
	@Override
	public int updateTerminal(Terminal terminal) {
		int result = 0;
		try {
			terminal.setUpdateBy(ShiroUtils.getSysUser().getUserId().toString());
			terminal.setUpdateTime(new Date());
			result = terminalMapper.updateTerminal(terminal);
		} catch (Exception e) {
			result = 0;
			e.printStackTrace();
		}
		return result;
	}

	/**
     * 删除终端
     * 
     * @param ids 终端id集合
     * @return 操作结果
     */
	@Override
	public int deleteTerminalByIds(String ids) {
		int result = 0;
		try {
			Integer[] intArray = Convert.toIntArray(ids);
	        result = terminalMapper.deleteTerminalByIds(intArray);
		} catch (Exception e) {
			result = 0;
			e.printStackTrace();
		}
		return result;
	}

	/**
     * 根据终端Id远程
     * 
     * @param id 终端id
     * @return 操作结果
     */
	@Override
	public int rangTerminal(int id) {
		Terminal terminal = terminalMapper.selectTerminalById(id);
		int result = 0;
		try {
			Bootstrap bootstrap = new Bootstrap();
			EventLoopGroup group = new NioEventLoopGroup();
			bootstrap.group(group).channel(NioSocketChannel.class)
					.option(ChannelOption.TCP_NODELAY, true)
					.handler(new ChannelInitializer<SocketChannel>() {
						@Override
						public void initChannel(SocketChannel ch) throws Exception {
							ChannelPipeline pipeline = ch.pipeline();
							pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
							//设置通道消息自定义解码器及业务处理
							pipeline.addLast(new ImageDecoder(), new ClientHandler());
						}
					});
			Channel channel = bootstrap.connect(terminal.getServiceUrl(),terminal.getPort()).sync().channel();
			if(null!=channel) {
				MyPanel panel = new MyPanel();
				String panelId = panel.hashCode() < 0 ? String.valueOf(-panel.hashCode()) : String.valueOf(panel.hashCode());
				if(RemoteDesktop.panelMap.get(panelId)==null) {
					RemoteDesktop.panelMap.put(panelId, panel);
				}
				String message = String.format("%20s", "ACK");
				message = message+String.format("%20s", String.valueOf(panelId));
				channel.writeAndFlush(message + '\n');
				 
				// initial frame
				JFrame frame = new JFrame();
				//设置滚动
				panel.setAutoscrolls(true);
				frame.add(panel);
				frame.setSize(1920, 1080);
				frame.setTitle("视可视远程控制终端");
				ClientNetty netty = new ClientNetty();;
				//加入鼠标键盘监听
				netty.setPanel(panel);
				netty.setChannel(channel);
				netty.setPanelId(String.format("%20s", String.valueOf(panelId)));
				RemoteMouseListener remoteMouseListener = new RemoteMouseListener(netty);
				RemoteKeyListener remoteKeyListener = new RemoteKeyListener(netty);
				panel.addMouseListener(remoteMouseListener);
				panel.addMouseMotionListener(remoteMouseListener);
				panel.addMouseWheelListener(remoteMouseListener);
				panel.addKeyListener(remoteKeyListener);
				//增加关闭窗口监听 关闭窗口则关闭通道
				frame.addWindowListener(new WindowAdapter() {
					@Override
			          public void windowClosing(WindowEvent e)
			          {
						channel.close();
			          }
				});
				frame.setVisible(true);
			}
		} catch (InterruptedException e) {
			result = 0;
			e.printStackTrace();
		}
		return result;
	}

	public static void main(String[] args) {
		try {
			Bootstrap bootstrap = new Bootstrap();
			EventLoopGroup group = new NioEventLoopGroup();
			bootstrap.group(group).channel(NioSocketChannel.class)
					.option(ChannelOption.TCP_NODELAY, true)
					.handler(new ChannelInitializer<SocketChannel>() {
						@Override
						public void initChannel(SocketChannel ch) throws Exception {
							ChannelPipeline pipeline = ch.pipeline();
							pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
							//设置通道消息自定义解码器及业务处理
							pipeline.addLast(new ImageDecoder(), new ClientHandler());
						}
					});
			Channel channel = bootstrap.connect("192.168.136.92",8091).sync().channel();
			if(null!=channel) {
				MyPanel panel = new MyPanel();
				String panelId = panel.hashCode() < 0 ? String.valueOf(-panel.hashCode()) : String.valueOf(panel.hashCode());
				if(RemoteDesktop.panelMap.get(panelId)==null) {
					RemoteDesktop.panelMap.put(panelId, panel);
				}
				String message = String.format("%20s", "ACK");
				message = message+String.format("%20s", String.valueOf(panelId));
				channel.writeAndFlush(message + '\n');

				// initial frame
				JFrame frame = new JFrame();
				//设置滚动
				panel.setAutoscrolls(true);
				frame.add(panel);
				frame.setSize(1920, 1080);
				frame.setTitle("视可视远程控制终端");
				ClientNetty netty = new ClientNetty();;
				//加入鼠标键盘监听
				netty.setPanel(panel);
				netty.setChannel(channel);
				netty.setPanelId(String.format("%20s", String.valueOf(panelId)));
				RemoteMouseListener remoteMouseListener = new RemoteMouseListener(netty);
				RemoteKeyListener remoteKeyListener = new RemoteKeyListener(netty);
				panel.addMouseListener(remoteMouseListener);
				panel.addMouseMotionListener(remoteMouseListener);
				panel.addMouseWheelListener(remoteMouseListener);
				panel.addKeyListener(remoteKeyListener);
				//增加关闭窗口监听 关闭窗口则关闭通道
				frame.addWindowListener(new WindowAdapter() {
					@Override
					public void windowClosing(WindowEvent e)
					{
						channel.close();
					}
				});
				frame.setVisible(true);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

    
}
